package com.jhecis.common;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhecis.dto.RequestHeader;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**register.RestSharpPost
 * Js脚本中Java方法在此类中添加
 */
@Component
public class RegisterFunction {
    /**
     *日志
     * js中使用【register.log('')】调用
     * @param msg
     */
    public void consoleLog(String msg){
        System.out.println("java中控制台输出:"+msg);
    }

    /**
     * 发送RestGet请求
     * @param path 路径
     * @param param 子路径
     * @param headers head
     * @return
     */
    public String RestSharpGet(String path, String param,String headers) {
        String data = "";
        String lasturl =  path + param;
        List<RequestHeader> headList=null;
        System.out.println(headers);
        if (headers!=null){
            ObjectMapper mapper = new ObjectMapper();
            try {
                JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, RequestHeader.class);
                headList= (List<RequestHeader>) mapper.readValue(headers, javaType);
            }
            catch (Exception e){
                System.out.println("header报错");
            }
        }
        try{
            URL url = new URL(lasturl);
            //打开和url之间的连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            //请求头
            urlConn.setRequestProperty("Accept-Charset", "utf-8");
            urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            if (headList!=null){
                headList.forEach(item->{
                    urlConn.setRequestProperty(item.Name, item.Value);
                });
            }
            //urlConn.setRequestProperty("auth","jhecis");
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.setRequestMethod("GET");//GET和POST必须全大写
            urlConn.connect();

            int code = urlConn.getResponseCode();//获得响应码
            if(code == 200) {//响应成功，获得响应的数据
                //InputStream is = urlConn.getInputStream();//得到数据流（输入流）
                //byte[] buffer = new byte[1024];
                //int length = 0;
                //while ((length = is.read(buffer)) != -1) {
                //	String res = new String(buffer, 0, length);
                //	data += res;
                //}
                //System.out.println(data);

                //解决中文乱码
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
                //data = reader.readLine();

                //解决返回参数换行问题，一次读一行，读入null时文件结束
                int line = 1;
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    data += tempString;
                    //把当前行号显示出来
                    //System.out.println("line " + line + ": " + tempString);
                    line++;
                }
                reader.close();

            }
            urlConn.disconnect();   //断开连接

        }catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }


    /**
     * 发送RestPost请求
     * @param path 路径
     * @param param 子路径
     * @param Data body数据
     * @param headers 请求头
     * @return
     */
    public String RestSharpPost(String path, String param,String Data,String headers) {
        String data = "";
        String lasturl =  path + param;
        List<RequestHeader> headList=null;
        System.out.println(headers);
        if ( StringUtils.isNotBlank(headers)){
            ObjectMapper mapper = new ObjectMapper();
            try {
                JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, RequestHeader.class);
                headList= (List<RequestHeader>) mapper.readValue(headers, javaType);
            }
            catch (Exception e){
                System.out.println("header报错");
            }
        }
        try{
            URL url = new URL(lasturl);
            //打开和url之间的连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            //请求头
            urlConn.setRequestProperty("Accept-Charset", "utf-8");
            urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            if (headList!=null){
                headList.forEach(item->{
                    urlConn.setRequestProperty(item.Name, item.Value);
                });
            }
            //urlConn.setRequestProperty("auth","jhecis");
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.setRequestMethod("POST");//GET和POST必须全大写
            urlConn.connect();
            //报文 解决中文乱码
            OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
            os.write(Data);
            os.flush();
            int code = urlConn.getResponseCode();//获得响应码
            if(code == 200) {//响应成功，获得响应的数据
                //解决中文乱码
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
                int line = 1;
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    data += tempString;
                    //把当前行号显示出来
                    //System.out.println("line " + line + ": " + tempString);
                    line++;
                }
                reader.close();
            }
            urlConn.disconnect();   //断开连接
        }catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
